package org.xiaoyu.feign.core;

import static feign.Util.checkNotNull;
import static feign.Util.emptyToNull;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import feign.Request;
import feign.RequestTemplate;
import feign.Target;

public class CustomTarget<T> implements Target<T> {

	private final Class<T> type;

	private final String name;

	private List<String> urls = new ArrayList<>();

	public CustomTarget(Class<T> type, ArrayList<String> urls) {
		this(type, "default", urls);
	}
	public CustomTarget(Class<T> type, String name) {
		this(type, name, new ArrayList<>());
	}
	public CustomTarget(Class<T> type, String name, ArrayList<String> urls) {
		this.type = checkNotNull(type, "type");
		this.name = checkNotNull(emptyToNull(name), "name");
		if (urls.size() > 0) {
			this.urls = urls;
		}
	}
	
	private String readUrl() {
		List<String> u = null;
		String ip = null;
		if(urls.size() > 0) {
			u = urls;
			Random random = new Random();
			int randomPos = random.nextInt(u.size());
			ip = u.get(randomPos);
		}else { 
			ip = name;
		}
		return ip;
	}

	@Override
	public Class<T> type() {
		return type;
	}

	@Override
	public String name() {
		return name;
	}

	@Override
	public String url() {
		return readUrl();
	}

	@Override
	public Request apply(RequestTemplate input) {
		if (input.url().indexOf("http") != 0) {
			input.insert(0, url());
		}
		return input.request();
	}

	@Override
	public boolean equals(Object obj) {
		if (obj instanceof CustomTarget) {
			CustomTarget<?> other = (CustomTarget<?>) obj;
			return type.equals(other.type) && name.equals(other.name) && urls.equals(other.urls);
		}
		return false;
	}

	@Override
	public int hashCode() {
		int result = 17;
		result = 31 * result + type.hashCode();
		result = 31 * result + name.hashCode();
		result = 31 * result + urls.hashCode();
		return result;
	}

}
